iT邦幫忙

2026 iThome 鐵人賽

DAY 5
0

前幾天我們鋪好了像素地板,但它目前看起來毫無生氣。HD-2D 風格最迷人的地方,就在於「復古像素」與「現代光影」的強烈碰撞。今天我們要為這個空間導入 Three.js 的光照系統,利用冷暖光影的交織,瞬間把一塊平淡無奇的平面變成充滿氛圍的地下城遺跡。

【撕下無光材質,換上標準材質】

請打開你的 src/main.js,找到昨天建立地板材質的地方。
將原本的 MeshBasicMaterial 更改為 MeshStandardMaterial。這個材質會根據環境的光線來決定明暗。

// 更改前:const material = new THREE.MeshBasicMaterial({ ... });
// 更改後:使用標準材質
const material = new THREE.MeshStandardMaterial({ 
  map: floorTexture, 
  side: THREE.DoubleSide 
});

【Step 2:打下基礎的環境光 (AmbientLight)】
在深邃的地下城裡,我們需要一點微弱的底光,才不會伸手不見五指。環境光會均勻地照亮場景中的每一個角落,不會產生陰影。

在 scene.add(floor); 的下方,加入這段環境光設定:

// 加入環境光:設定為偏冷的幽暗紫藍色,強度設為 1.5
const ambientLight = new THREE.AmbientLight('#404059', 1.5);
scene.add(ambientLight);

【Step 3:點燃第一盞火把 (PointLight)】
接下來是建立立體感的重頭戲。我們要在大廳的正中央懸掛一盞「點光源」,它就像是一盞火把或魔法提燈,光線會由中心向外衰減。

接著在環境光的下方,加入這段點光源設定:

// 加入點光源:設定為暖橘色,光照強度 20,照射距離 10
const pointLight = new THREE.PointLight('#ffaa00', 20, 10);
// 將光源放置在場景正中央 (x:0, z:0),高度稍微抬升 (y:2)
pointLight.position.set(0, 2, 0);
scene.add(pointLight);

// (可選) 視覺化光源位置,方便除錯:加一顆小球代表火把的位置
const lightHelper = new THREE.PointLightHelper(pointLight, 0.2);
scene.add(lightHelper);

day5 完整程式碼

// ... (上半部場景、攝影機、控制器的設定不變) ...

const textureLoader = new THREE.TextureLoader();
const floorTexture = textureLoader.load('/floor.png');
floorTexture.magFilter = THREE.NearestFilter; 
floorTexture.wrapS = THREE.RepeatWrapping; 
floorTexture.wrapT = THREE.RepeatWrapping; 
floorTexture.repeat.set(10, 10);           

// 鋪設 3D 地板 (升級為 MeshStandardMaterial)
const geometry = new THREE.PlaneGeometry(10, 10);
const material = new THREE.MeshStandardMaterial({ 
  map: floorTexture, 
  side: THREE.DoubleSide 
});
const floor = new THREE.Mesh(geometry, material);
floor.rotation.x = -Math.PI / 2; 
scene.add(floor);

// ----------------- 新增光影系統 -----------------

// 1. 環境光 (幽暗冷色底光)
const ambientLight = new THREE.AmbientLight('#404059', 1.5);
scene.add(ambientLight);

// 2. 點光源 (中央暖橘色火把光)
const pointLight = new THREE.PointLight('#ffaa00', 20, 10);
pointLight.position.set(0, 2, 0);
scene.add(pointLight);

// 光源位置輔助工具 (那顆發光的方形小框框)
const lightHelper = new THREE.PointLightHelper(pointLight, 0.2);
scene.add(lightHelper);

// ... (下半部 animate 渲染迴圈不變) ...

【本日結語】
回到瀏覽器看看!原本死板的地板,現在中央會凝聚一團溫暖的橘色光暈,邊緣則會漸隱進入幽藍色的深淵中。
image


上一篇
Day 4:賦予像素靈魂與上帝視角!TextureLoader 與 OrbitControls
下一篇
Day 6:捨棄上帝之手!打造俯視視角與邊界牆壁
系列文
Three.js × WebGL 實戰:打造 HD-2D 像素地下城與即時光影系統 共 17 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言